﻿/*******************************************************************************
 * Copyright © 2016-2020 北京网非科技有限公司 版权所有
 * Author: 北京网非科技有限公司
 * Description: 网非快速开发平台NET
 * Website：http://www.wfdot.com
*********************************************************************************/
using CubicFWNet.Common;
using CubicFWNet.Data.SystemManage;
using CubicFWNet.Data.SystemManage.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CubicFWNet.Application.SystemManage
{
    public class RoleApp
    {
        private RoleRepository _roleRepository;
        private RelevanceRepository _relevanceRepository;
        public RoleApp()
        {
            _relevanceRepository = new RelevanceRepository();
            _roleRepository = new RoleRepository();
        }

        public Role GetForm(Guid id)
        {
            return _roleRepository.FindEntity(id);
        }

        public IEnumerable<Role> Load()
        {
            return _roleRepository.IQueryable().OrderBy(a => a.SortNo);
        }

        public IEnumerable<Role> GetList(string keyWord)
        {
            var expression = ExtLinq.True<Role>();
            if (!string.IsNullOrEmpty(keyWord))
            {
                expression = expression.And(t => t.Name.Contains(keyWord));
            }
            return _roleRepository.IQueryable(expression).OrderByDescending(u => u.SortNo);
        }

        /// <summary>
        /// 加载一个角色的全部 模块Ids
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<Guid> Load(Guid roleId)
        {
            List<Guid> modules = new List<Guid>();
            if (roleId == Guid.Empty)
            {
                return modules;
            }
            return _relevanceRepository.LoadByRoleId(roleId).ToList();
        }

        public void AddOrUpdate(Role role, string[] moduleIds)
        {
            if (role.Id == Guid.Empty)
            {
                role.Id = Guid.NewGuid();
                _roleRepository.Insert(role);
            }
            else
            {
                _roleRepository.Update(role);
            }
            //更新用户的模块
            var secIds = moduleIds.Where(a => !string.IsNullOrWhiteSpace(a)).Select(a => Guid.Parse(a)).ToArray();
            var type = "RoleModule";
            _relevanceRepository.DeleteBy(type, role.Id);
            _relevanceRepository.AddRelevance(type, secIds.ToLookup(u => role.Id));
        }


        public ResponseResult Delete(Guid id)
        {
            var del = _roleRepository.FindEntity(id);
            if (del == null) 
                return new ResponseResult { Status = ResultType.error.ToString(), Message = "未找到该数据", Data = id };
            _roleRepository.Delete(del);
            return new ResponseResult { Status = ResultType.success.ToString(), Data = id };
        }


    }
}
